package com.cxh.rmsq.ui.activity.self

import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.net.toUri
import androidx.lifecycle.ViewModelProviders
import com.cxh.rmsq.R
import com.cxh.rmsq.db.model.AuthenticationBean
import com.cxh.rmsq.im.IMManager
import com.cxh.rmsq.model.Status
import com.cxh.rmsq.ui.BaseActivity
import com.cxh.rmsq.utils.RegexUtils
import com.cxh.rmsq.utils.ToastUtils
import com.cxh.rmsq.viewmodel.SecurityViewModel
import com.cxh.rmsq.viewmodel.UserInfoViewModel
import coil.load
import coil.transform.RoundedCornersTransformation
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ColorUtils
import com.cxh.rmsq.model.Resource2
import com.cxh.rmsq.model.Result2
import com.cxh.rmsq.ui.dialog.PhotoDialog

class AuthenticationActivity : BaseActivity(), View.OnClickListener {

    private val ivBack: LinearLayout by lazy { findViewById<LinearLayout>(R.id.iv_back) }
    private val ivPhotoZ: ImageView by lazy { findViewById<ImageView>(R.id.iv_photo_z) }
    private val ivPhotoF: ImageView by lazy { findViewById<ImageView>(R.id.iv_photo_f) }
    private val tvSubmit: TextView by lazy { findViewById<TextView>(R.id.tv_submit) }
    private val etIdName: EditText by lazy { findViewById<EditText>(R.id.et_id_name) }
    private val etIdNumber: EditText by lazy { findViewById<EditText>(R.id.et_id_number) }
    private val ivIdF: ImageView by lazy { findViewById<ImageView>(R.id.iv_id_f) }
    private val ivIdZ: ImageView by lazy { findViewById<ImageView>(R.id.iv_id_z) }

    var zmPhoto = ""
    var fmPhoto = ""
    var id = 0
    var type = 0
    private var photoDialog: PhotoDialog? = null
    private var securityViewModel: SecurityViewModel? = null
    private var userInfoViewModel: UserInfoViewModel? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_authentication)
        findViewById<LinearLayout>(R.id.cl_toolbar).setPadding(0, BarUtils.getStatusBarHeight(), 0, 0)
        BarUtils.setStatusBarColor(this, ColorUtils.getColor(R.color.transparent))
        BarUtils.setStatusBarLightMode(this, true)

        ivBack.setOnClickListener(this)
        ivPhotoZ.setOnClickListener(this)
        ivPhotoF.setOnClickListener(this)
        tvSubmit.setOnClickListener(this)
    }

    override fun onResume() {
        super.onResume()
        securityViewModel = ViewModelProviders.of(this).get(SecurityViewModel::class.java)
        userInfoViewModel =
            ViewModelProviders.of(this).get<UserInfoViewModel>(UserInfoViewModel::class.java)

        userInfoViewModel!!.upload()
            .observe(this@AuthenticationActivity) { resource: Resource2<String?> ->
                if (resource.status == Status.SUCCESS && resource.data != null) {
                    if (type == 1) {
                        fmPhoto = resource.data.toString()
                    } else {
                        zmPhoto = resource.data.toString()
                    }
                }
            }


        securityViewModel!!.getAuthentication(IMManager.getInstance().currentId)
        securityViewModel!!.authentication.observe(this@AuthenticationActivity) { resource: Result2<AuthenticationBean> ->
//            if (resource.status == Status.SUCCESS && resource.data != null) {
                if (resource.result != null) {
                    val data = resource.result!!
                    etIdName.setText(data.realName)
                    etIdNumber.setText(data.idNumber)

                    ivIdZ.load(data.zmPhoto) {

                        transformations(RoundedCornersTransformation())
//                      placeholder(R.mipmap.icon_picture_backup)
//                      error(R.mipmap.icon_picture_backup)
                    }
                    ivIdF.load(data.fmPhoto) {
                        transformations(RoundedCornersTransformation())
//                      placeholder(R.mipmap.icon_picture_backup)
//                      error(R.mipmap.icon_picture_backup)
                    }
                    id = data.id
                    zmPhoto = data.zmPhoto.toString()
                    fmPhoto = data.fmPhoto.toString()
                    when (data.status) {
                        "1"/*, "2" */ -> {
                            etIdName.isEnabled = false
                            etIdNumber.isEnabled = false
                            ivPhotoZ.visibility = View.GONE
                            ivPhotoF.visibility = View.GONE
                            tvSubmit.visibility = View.GONE
                        }
                    }

                }
//            }
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_back -> {
                finish()
            }

            R.id.iv_photo_z -> {
//                if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//                    // 显示对话框告知用户权限使用目的
//                    val builder: AlertDialog.Builder = AlertDialog.Builder(this)
//                    builder.setTitle("权限申请")
//                        .setMessage("我们需要访问您的相机、存储权限，以便于图片上传、好友间发送照片以及实名认证等操作")
//                        .setPositiveButton("允许",
//                            DialogInterface.OnClickListener { dialog, which ->
//                                AppPermissionUtil.requestPermissions(this@AuthenticationActivity,
//                                    arrayOf<String>(
//                                        Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE
//                                    ),
//                                    object : AppPermissionUtil.OnPermissionListener {
//                                        override fun onPermissionGranted() {
//                                            initAvatar()
//                                            photoDialog?.show()
//                                        }
//
//                                        override fun onPermissionDenied() {
//
//                                        }
//
//                                    })
//                            })
//                        .setNegativeButton(
//                            "拒绝",
//                            DialogInterface.OnClickListener { dialog, which ->
//                                // 用户拒绝权限申请
//                            })
//                        .show()
//                } else {
                    // 已获得权限，执行相关操作
                    initAvatar()
                    photoDialog?.show()
//                }

            }

            R.id.iv_photo_f -> {
                    initAvatar(1)
                    photoDialog?.show()
            }

            R.id.tv_submit -> {
                val idName = etIdName.text.toString()
                if (TextUtils.isEmpty(idName)) {
                    ToastUtils.showToast("请输入真实姓名")
                    return
                }
                val idNumber = etIdNumber.text.toString()
                if (TextUtils.isEmpty(idNumber)) {
                    ToastUtils.showToast("请输入15位或18位身份证号码")
                    return
                }
                if (!RegexUtils.checkIdCard(idNumber)) {
                    ToastUtils.showToast("请输入正确的手机号")
                    return
                }
                if (TextUtils.isEmpty(zmPhoto)) {
                    ToastUtils.showToast("请上传身份证正面")
                    return
                }
                if (TextUtils.isEmpty(fmPhoto)) {
                    ToastUtils.showToast("请上传身份证反面")
                    return
                }
                if (id > 0) {
                    userInfoViewModel!!.submitAuthentication(
                        IMManager.getInstance().currentId,
                        id.toString(),
                        idName,
                        idNumber,
                        zmPhoto,
                        fmPhoto
                    )
                } else {
                    userInfoViewModel!!.submitAuthentication(
                        IMManager.getInstance().currentId,
                        null,
                        idName,
                        idNumber,
                        zmPhoto,
                        fmPhoto
                    )
                }
                userInfoViewModel!!.submitAuthentication()
                    .observe(this@AuthenticationActivity) { resource: Resource2<String?> ->
                        if (resource.data != null) {
                            ToastUtils.showToast("认证已提交")
                            finish()
                        } else {
                            ToastUtils.showToast(resource.msg)
                        }
                    }
//                viewModel.setAuthentication(id.toString(), idName, idNumber, zmPhoto, fmPhoto)
            }
        }
    }

    private fun initAvatar(type: Int = 0) {
        this.type = type
        if (photoDialog == null) {
            photoDialog =
                PhotoDialog(this@AuthenticationActivity, false, 1, 1, R.style.BottomDialog)
        }

        photoDialog?.setOnClickListener(object : PhotoDialog.OnClickListener {
            override fun onPhotoPathResult(images: MutableList<String>) {

                if (type == 1) {
                    ivIdF.setImageURI(images[0].toUri())
                } else {
                    ivIdZ.setImageURI(images[0].toUri())
                }
                Log.e("imggggg", images[0])

                userInfoViewModel!!.uploadImg(images[0])
//                viewModel.run {
//                    getFileUpdate(images[0])
//                }
            }

            override fun onCameraPathResult(images: MutableList<String>) {

                if (type == 1) {
                    ivIdF.setImageURI(images[0].toUri())
                } else {
                    ivIdZ.setImageURI(images[0].toUri())
                }
                userInfoViewModel!!.uploadImg(images[0])
//                viewModel.run {
//                    getFileUpdate(images[0])
////                    mBinding.ivHead.load(images[0]) {
////                        transformations(RoundedCornersTransformation())
//////                      placeholder(R.mipmap.icon_picture_backup)
//////                      error(R.mipmap.icon_picture_backup)
////                    }
//                }
            }

        })
    }

}